package com.czy.service.impl;

import com.czy.dto.UserCheckinDto;
import com.czy.entity.CheckinRecord;
import com.czy.mapper.CheckinRecordMapper;
import com.czy.service.CheckinRecordService;
import com.czy.utils.BeanCopyUtils;
import com.czy.utils.ThreadLocalUtils;
import com.czy.vo.CaptchaVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
import java.util.stream.Collectors;

@Service
public class CheckinRecordServiceImpl implements CheckinRecordService {
    @Autowired
    private CheckinRecordMapper checkinRecordMapper;

    /**
     * 生产随机验证码
     */
    @Override
    public CaptchaVo randomNum() {
        return new CaptchaVo(number());
    }

    /**
     * 添加签到信息
     */
    @Override
    public void insertCheckin(UserCheckinDto userCheckinDto) {

        //将相同的字段进行拷贝
        CheckinRecord checkinRecord = BeanCopyUtils.copyBean(userCheckinDto, CheckinRecord.class);

        //签到状态
        if (userCheckinDto.getStatus().equals("上班")) {
            checkinRecord.setStatus(1);
        } else {
            checkinRecord.setStatus(2);
        }

        //补全基础属性用户ID和签到时间
        checkinRecord.setUserId(Long.valueOf(ThreadLocalUtils.getCurrentId()));
        checkinRecord.setCheckinTime(LocalDateTime.now());


        checkinRecordMapper.insertCheckin(checkinRecord);
    }

    private String number() {
        Random random = new Random();

        char[] arr = new char[52];
        //获取所有的大小写字母
        for (int i = 0; i < arr.length; i++) {
            if (i < 26) {
                arr[i] = (char) ('a' + i);
            } else {
                arr[i] = (char) ('A' + i - 26);
            }
        }
        //获取三个大小字母
        ArrayList<String> list = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            int index = random.nextInt(52);
            list.add(arr[index] + "");
        }

        //添加一个随机数字
        list.add(random.nextInt(10) + "");

        //打乱
        Collections.shuffle(list);

        //如何将数组转换为字符串
        String result = list.stream()
                .map(String::valueOf)
                .collect(Collectors.joining());
        return result;
    }
}
